#!/bin/bash

: <<'example'
curl -sSL https://gitee.com/sunnybug/pubshell/raw/main/net/docker_net.sh | bash
example

# 配置Docker镜像加速器的通用函数[国内镜像基本被封杀]
configure_docker_mirror() {
    local conf="$1"
    echo '[...]配置Docker镜像...'

    if grep -q "https://192.168.1.185:5007" "${conf}"; then
        echo "镜像 https://192.168.1.185:5007 已经正确配置，无需修改"
        return
    fi

    # 备份现有配置
    if [ -f "$conf" ]; then
        mv "$conf" "${conf}.bak.$(date +"%Y%m%d%H%M%S")"
        g_Change=true
    fi

    # 确保配置目录存在
    mkdir -p "$(dirname "$conf")"

    # 写入镜像配置
    cat <<EOF >"$conf"
{
    "registry-mirrors": [
        "https://192.168.1.185:5007"
    ]
}
EOF
}

# root模式下配置镜像加速
docker_root_mirror() {
    configure_docker_mirror "/etc/docker/daemon.json"
    echo "[SUC]镜像加速器配置完成: $conf"
    echo "[...]重启Docker服务..."
    systemctl restart docker
    echo "[SUC]Docker服务重启完成"
}

# rootless模式下配置镜像加速
docker_rootless_mirror() {
    configure_docker_mirror "$HOME/.config/docker/daemon.json"
    echo "[SUC]镜像加速器配置完成: $conf"
    echo "[...]重启Docker服务..."
    systemctl --user restart docker
    echo "[SUC]Docker服务重启完成"
}

# 检查是否是rootless模式
if docker info | grep -q "rootless"; then
    docker_rootless_mirror
else
    docker_root_mirror
fi
